package com.example.esaclient;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public  class TabUserTimeline extends ListFragment {			
	 
	  View fragView;	  
	  Integer esaUsrID=0;
	  SimpleAdapter adapter;
	  ArrayList<HashMap<String, Object>> data;
	  Boolean LoggedToTwitter=false,LoggedToFacebook=false,LoggedToGoogle=false;
	  
	  // Progress dialog
	    ProgressDialog dialog;
	    
	    //listView
	    ListView lv;
	    int position,top=0;
	    boolean loadingMore=true;
	    static int count,size = 0;
	    int lastPostViewed=0;
	    int oldItemCount=0;
	    static int N_ITEMS_TO_LOAD=10;
	    
	  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   	 
           
           fragView = inflater.inflate(R.layout.tabscontent, container, false);           
          esaUsrID=new GlobalSettings(this.getActivity()).getPrefInt(GlobalSettings.PREF_ESA_USRID);   
          refresh();
            return fragView;
    }

    

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

  	  //View footerView =inflater.inflate(R.layout.footer, null, false);
        //lv.addFooterView(footerView);
  	lv= getListView();
  	
  	lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            // TODO Auto-generated method stub

          final HashMap<String, Object> elem=data.get(pos);
          AlertDialog.Builder dialog = new AlertDialog.Builder(TabUserTimeline.this.getActivity());
         // dialog.setTitle(elem.get("tagger").toString());
          dialog.setMessage(elem.get("message").toString());
          dialog.setPositiveButton(" Share on Facebook ", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  dialog.dismiss(); 
                  String msg = "On " + elem.get("time").toString() + " I've shared on"+ elem.get("socialNetwork").toString().replace("Via", "") +": \n \""+elem.get("message").toString()+ "\"";
                  
                  try {
					new CrossPostingFB(TabUserTimeline.this.getActivity()).execute(esaUsrID,URLEncoder.encode(msg, "utf-8"));
				} catch (UnsupportedEncodingException e) {
				
					e.printStackTrace();
				}

              }
              
          });
          
          dialog.setNegativeButton("Re-tweet", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  dialog.dismiss();
                  String msg = "I've shared on"+ elem.get("socialNetwork").toString().replace("Via", "") +":\n"+elem.get("message").toString();
                  //limit to 140 chars
                  msg=msg.substring(0, Math.min(msg.length(), 140));
                  try {
					new CrossPostingTW(TabUserTimeline.this.getActivity()).execute(esaUsrID,URLEncoder.encode(msg, "utf-8"));
				} catch (UnsupportedEncodingException e) {
				
					e.printStackTrace();
				}
              }
          });
          dialog.show();
     
            return true;
        }
    }); 

         this.getListView().setOnScrollListener(new OnScrollListener() {
             @Override
             public void onScrollStateChanged(AbsListView view, int scrollState) {
             }

             @Override
             public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {

                 position = firstVisibleItem;
                 View v = lv.getChildAt(0);
                 top = (v == null) ? 0 : v.getTop();
                 int lastInScreen = firstVisibleItem + visibleItemCount;
                
              
                 if ((lastInScreen == totalItemCount) && !(loadingMore) && (oldItemCount!=totalItemCount)) {
                    
                         try {loadingMore=true;
                         lastPostViewed=lastInScreen;
                         System.out.println("Last Before->" +lastPostViewed);
                        	  System.out.println("Calling WS:" + totalItemCount +"->"+(totalItemCount+N_ITEMS_TO_LOAD));
                      		new GetMyPosts(TabUserTimeline.this).execute(esaUsrID, "", totalItemCount,totalItemCount+N_ITEMS_TO_LOAD);
                      		oldItemCount=totalItemCount;
                         } catch (Exception e) {
                             e.printStackTrace();
                         }

                 }
             }
         });
         
    
    }
    
	public void refresh() {
		
		dialog = ProgressDialog.show(this.getActivity(), "", "Contacting Esa Server. Please, Wait...", true);
		dialog.setCancelable(true);
		dialog.show(); 
		
		oldItemCount=0;
		
		//TODO: usare GetServicesOn
	
		GlobalSettings gs = new GlobalSettings(this.getActivity());
		LoggedToTwitter = gs.getPrefBool(GlobalSettings.PREF_KEY_TWITTER_LOGIN);
		LoggedToFacebook = gs.getPrefBool(GlobalSettings.PREF_KEY_FACEBOOK_LOGIN);
		LoggedToGoogle = gs.getPrefBool(GlobalSettings.PREF_KEY_GOOGLE_LOGIN);

		// Toast.makeText(this.getActivity(), "Loading...", Toast.LENGTH_SHORT).show();	
		
		if(data!=null){
			data.clear();
			adapter.notifyDataSetChanged();}
		
		if (LoggedToFacebook || LoggedToTwitter || LoggedToGoogle){
			loadingMore=true;
			new GetMyPosts(this).execute(esaUsrID, "", 0, N_ITEMS_TO_LOAD);
			}
		else
			{
			//	Toast.makeText(this.getActivity(), "There are no posts.", Toast.LENGTH_LONG).show();
				dialog.dismiss();
			}
	}
    
	public void fillList(String[] result){
		
		EsaPost ep;
		if(data==null)
		data=new ArrayList<HashMap<String,Object>>();
		
		
		//TODO: Just for DEMO purpose
	/*	EsaPost[] e={new EsaPost("#test Twitter.+-+20/06/2013 08:37:54+-+Twitter+-++-+0+-+0+-+0"),
					 new EsaPost("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce varius sit amet erat iaculis gravida. Aenean volutpat aliquam turpis posuere.+-+05/05/2013 17:11:19+-+Facebook+-++-+2+-+0+-+0"),
					 new EsaPost("I am a tweet. I have exactly 140 characters. If you want to make sure that I only have 140 characters you can check for yourself. 0123456789+-+25/03/2013 12.05.00+-+Twitter+-++-+5+-+10+-+"),
					 new EsaPost("Ночью зрите хочет сияют чтобы. Лия одр кое тук Уже Чем. Ах забыли создан Уж Тя голубь им мя. Изобразить бессильным облеченный умудряться сотворится.+-+25/03/2013 12.05.00+-+Twitter+-++-+5+-+10+-+"),
					 new EsaPost("Winter is coming+-+25/03/2013 12.05.00+-+Facebook+-++-+5+-+10+-+"),
					 new EsaPost("事 ，可 去 覽 誨 」. 誨 矣 意 ，可 去. 矣 曰： 關雎 事 去. 出 事 關雎 ，可 去 」 曰： 矣. 」 出 曰： 事 意 耳 關雎 誨. 冒認收了 吉安而來 汗流如雨 父親回衙 玉，不題. +-+25/03/2013 12.05.00+-+Twitter+-++-+5+-+10+-+")};		
		*/
		
		if(result.length>0){
		for (int i = 0; i < result.length; i++) // !!check SN login status
		{
			if (result[i] != null) {
				ep = new EsaPost(result[i]);
				// data.add(ep.feed); }
				if (ep.socialNetwork.equals("Twitter") && LoggedToTwitter)
					data.add(ep.feed);
				else if (ep.socialNetwork.equals("Facebook")&& LoggedToFacebook)
					data.add(ep.feed);
				else if (ep.socialNetwork.equals("Google") && LoggedToGoogle)
					data.add(ep.feed);
			}
		}
		String[] from = { "message", "time", "socialNetwork", "picture",
				"n_likes", "n_comments" }; // from values of hashMap
		int[] to = { R.id.lstMsg, R.id.lstTime, R.id.lstFrom,
				R.id.lstImage, R.id.lstLikes, R.id.lstCommens };// to id of view
	      
        adapter=new SimpleAdapter(
                       this.getActivity().getApplicationContext(),
                        data,//data source
                        R.layout.feed_element, //layout of a single feed element
                        from,
                        to);
		
      lv.setAdapter(adapter);
      adapter.notifyDataSetChanged();
      System.out.println("Last After->" +lastPostViewed);
      lv.setSelectionFromTop(position, top);
        
  	
		}
		
		
	loadingMore=false;

	
	}
	
	
	
	public void ClearList(){
		
		lastPostViewed=0;
		oldItemCount=0;
		ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
		
		
		
		EsaPost e=new EsaPost("");
					 
	
			data.add(e.feed);	
			
			
		 String[] from={"message","time","socialNetwork","picture","n_likes","n_comments"}; //from values of hashMap
	        int[] to={R.id.lstMsg,R.id.lstTime,R.id.lstFrom,R.id.lstImage,R.id.lstLikes,R.id.lstCommens};//to id of view
	        
	
        adapter=new SimpleAdapter(
                       this.getActivity().getApplicationContext(),
                        data,//data source
                        R.layout.feed_element, //layout of a single feed element
                        from,
                        to);
        
		
      getListView().setAdapter(adapter);
	}
	
	
	public void GetMyPostsResult(String[] result){
		if(dialog!=null)
		dialog.dismiss();
		fillList( result);
	}
	
	
	
}